import os

from PyQt6.QtCore import QThread, pyqtSignal

from ..ncm2mp3.ncm_cli import ncmdump_single_file


class NcmdumpThread(QThread):
    # 定义信号
    info_signal = pyqtSignal(str)
    finished_signal = pyqtSignal(str)
    error_signal = pyqtSignal(str)

    def __init__(self, input: str, output_dir: str):
        super().__init__()
        self.input = input
        self.output_dir = output_dir

    def run(self):
        try:
            if os.path.isfile(self.input):

                _, suffix = os.path.splitext(self.input)
                if suffix.lower() != '.ncm':
                    raise ValueError('请选择扩展名为 ncm 的文件')

                ncmdump_single_file(self.input, self.output_dir)
                self.finished_signal.emit(f"{os.path.basename(self.input) } finished\n")  # 发射任务完成信号

            elif os.path.isdir(self.input):

                for file in os.listdir(self.input):

                    abs = os.path.join(self.input, file)
                    if not os.path.isfile(abs):
                        continue

                    _, suffix = os.path.splitext(abs)
                    if suffix.lower() != '.ncm':
                        continue

                    ncmdump_single_file(abs, self.output_dir)
                    self.info_signal.emit(f"{os.path.basename(abs) } finished")  # 发射任务完成信号

                self.finished_signal.emit('所有转换完成\n')

            else:
                raise ValueError('输入文件不符合规范')
        except Exception as e:
            self.error_signal.emit(str(e))  # 发射异常信号
